import Vue from "vue"
import VueRouter from "vue-router"
import store from "@/store"

Vue.use(VueRouter)

const routes = [
  {
    path: "/",
    redirect: "/login"
  },
  {
    path: "/login",
    name: "Login",
    component: () => import("@/views/Login.vue")
  },
  {
    path: "/admin",
    component: () => import("@/views/AdminLayout.vue"),
    meta: { requiresAuth: true },
    children: [
      {
        path: "",
        redirect: "/admin/dashboard"
      },
      {
        path: "dashboard",
        name: "Dashboard",
        component: () => import("@/views/Dashboard.vue"),
        meta: { requiresAuth: true }
      },
      {
        path: "students",
        name: "Students",
        component: () => import("@/views/StudentManagement.vue"),
        meta: { requiresAuth: true }
      },
      {
        path: "admins",
        name: "Admins",
        component: () => import("@/views/AdminManagement.vue"),
        meta: { requiresAuth: true }
      },
      {
        path: "labor-types",
        name: "LaborTypes",
        component: () => import("@/views/LaborTypeManagement.vue"),
        meta: { requiresAuth: true }
      },
      {
        path: "labors",
        name: "Labors",
        component: () => import("@/views/LaborManagement.vue"),
        meta: { requiresAuth: true }
      },
      {
        path: "errands",
        name: "Errands",
        component: () => import("@/views/ErrandManagement.vue"),
        meta: { requiresAuth: true }
      },
      {
        path: "substitutes",
        name: "Substitutes",
        component: () => import("@/views/SubstituteManagement.vue"),
        meta: { requiresAuth: true }
      },
      {
        path: "express",
        name: "Express",
        component: () => import("@/views/ExpressManagement.vue"),
        meta: { requiresAuth: true }
      },
      {
        path: "banners",
        name: "Banners",
        component: () => import("@/views/BannerManagement.vue"),
        meta: { requiresAuth: true }
      },
      {
        path: "schools",
        name: "Schools",
        component: () => import("@/views/SchoolManagement.vue"),
        meta: { requiresAuth: true }
      },
      {
        path: "messages",
        name: "Messages",
        component: () => import("@/views/MessageManagement.vue"),
        meta: { requiresAuth: true }
      },
      {
        path: "settings",
        name: "Settings",
        component: () => import("@/views/SystemSettings.vue"),
        meta: { requiresAuth: true }
      },
      {
        path: "logs",
        name: "Logs",
        component: () => import("@/views/OperationLogs.vue"),
        meta: { requiresAuth: true }
      },
      {
        path: "second-hand-categories",
        name: "SecondHandCategories",
        component: () => import("@/views/SecondHandCategoryManagement.vue"),
        meta: { requiresAuth: true }
      },
      {
        path: "second-hand-products",
        name: "SecondHandProducts",
        component: () => import("@/views/SecondHandManagement.vue"),
        meta: { requiresAuth: true }
      }
    ]
  },
  {
    path: "/merchant",
    component: () => import("@/views/MerchantLayout.vue"),
    meta: { requiresAuth: true, userType: "merchant" },
    children: [
      {
        path: "",
        redirect: "/merchant/labor-publish"
      },
      {
        path: "labor-publish",
        name: "LaborPublish",
        component: () => import("@/views/LaborPublish.vue"),
        meta: { requiresAuth: true, userType: "merchant" }
      }
    ]
  }
]

const router = new VueRouter({
  mode: "history",
  base: process.env.BASE_URL,
  routes
})

// 路由守卫
router.beforeEach(async (to, from, next) => {
  // 获取token和用户类型
  const token = localStorage.getItem('token')
  const userType = localStorage.getItem('userType') || 'admin'
  
  if (token) {
    if (to.path === '/login') {
      // 如果已登录，根据用户类型重定向到对应主页
      if (userType === 'merchant') {
        next({ path: '/merchant/labor-publish' })
      } else {
        next({ path: '/admin/dashboard' })
      }
    } else {
      // 检查用户信息是否存在
      if (store.getters.getUserInfo) {
        // 检查路由权限
        if (to.meta.userType && to.meta.userType !== userType) {
          // 用户类型不匹配，重定向到对应主页
          if (userType === 'merchant') {
            next({ path: '/merchant/labor-publish' })
          } else {
            next({ path: '/admin/dashboard' })
          }
        } else {
          next()
        }
      } else {
        try {
          // 从localStorage获取用户信息
          const userInfo = localStorage.getItem('userInfo') || localStorage.getItem('adminInfo')
          if (userInfo) {
            const parsedUserInfo = JSON.parse(userInfo)
            store.dispatch('login', { ...parsedUserInfo, userType })
            
            // 检查路由权限
            if (to.meta.userType && to.meta.userType !== userType) {
              // 用户类型不匹配，重定向到对应主页
              if (userType === 'merchant') {
                next({ path: '/merchant/labor-publish' })
              } else {
                next({ path: '/admin/dashboard' })
              }
            } else {
              next()
            }
          } else {
            // 没有用户信息，重定向到登录页
            localStorage.removeItem('token')
            localStorage.removeItem('userType')
            next('/login')
          }
        } catch (error) {
          // 获取用户信息失败，清除token并跳转到登录页
          localStorage.removeItem('token')
          localStorage.removeItem('userInfo')
          localStorage.removeItem('adminInfo')
          localStorage.removeItem('userType')
          next('/login')
        }
      }
    }
  } else {
    // 没有token
    if (to.path === '/login') {
      // 在登录页，直接进入
      next()
    } else {
      // 不在登录页，重定向到登录页
      next('/login')
    }
  }
})

export default router
